const reportModel = require('../models/reports.model')
const logger = require('../utils/logger')
class ReportService {
  reports = reportModel
  async findAll ({ page = 1, pageSize = 100, place, unpassedItems, submitDate }) {
    const query = {
      deleted: false,
    }
    if (place) {
      query.place = {
        $in: place.split(',')
      }
    }
    if (unpassedItems) {
      query.unpassedItems = unpassedItems
    }
    if (submitDate) {
      query.submitDate = submitDate
    }
    const sort = {
      submitDate: -1
    }
    page = parseInt(page) || 1
    const limit = parseInt(pageSize) || 100
    const skip = (page - 1) * (limit)
    const data = await this.reports.find(query).sort(sort).skip(skip).limit(limit).populate('submitter').populate('place')
    const totalSize = await this.reports.countDocuments(query)
    return {
      data,
      totalSize
    }
  }
  findOne (id) {
    return this.reports.find({ deleted: false, _id: id }).populate('submitter').populate('place')
  }
  updateOne (id, data) {
    return this.reports.findOneAndUpdate({ _id: id }, data)
  }
  deleteOne (id) {
    return this.reports.findOneAndUpdate({ _id: id }, { deleted: true })
  }
  async addOne (doc) {
    // TODO check doc
    logger.info('report created ', doc)
    return await this.reports.create(doc)
  }
}

module.exports = ReportService